﻿#include "KLineAddBarFunction.h"
#include <QVector>
#include <QVariant>

#include "KLineSceneWidget.h"
#include "KLineCanvas.h"
#include "KLineView.h"
#include "KLineLayer.h"
#include "KLineBarLayer.h"
#include "KColorStyle.h"
#include "../TableInScene/VectorInterface.h"

class KLineAddBarFunction::KLineAddBarFunctionPrivate :QObject
{
public:
	int in_params[16];
	int out_params[1];
	int in_count;
	int out_count;
public:
	KLineAddBarFunctionPrivate(QObject*parent) :QObject(parent)
	{
		in_count = 6;
		out_count = 1;

		in_params[0] = FPT_PTR;				// scene pointer
		in_params[1] = FPT_STRING;			// view name
		in_params[2] = FPT_VECTOR;			// open
		in_params[3] = FPT_VECTOR;			// vector<variant>*close
		in_params[4] = FPT_VECTOR;			// vector<variant>*high
		in_params[5] = FPT_VECTOR;			// vector<variant>*low
		out_params[0] = FPT_NUMBER;			// return 0|1
	}
};

KLineAddBarFunction::KLineAddBarFunction(QObject *parent)
	: QObject(parent),private_ptr(new KLineAddBarFunctionPrivate(this))
{
}

KLineAddBarFunction::~KLineAddBarFunction()
{
}
QString KLineAddBarFunction::ID()
{
	return "KLineAddBar";
}
static int KLineAddBarFunction_FUNCTION(struct variant_s *in, int in_count, struct variant_s *out, void*tag)
{
	if (6 != in_count)
		return ERR_PARAM_NOT_MATCH;

	// 判断第一个参数
	if (VALUETYPE_VOID_PTR != in[0].type)
		return ERR_DATATYPE_NOT_MATCH;
	if (nullptr == in[0].u.ptr)
		return ERR_DATATYPE_NOT_MATCH;

	AstScene*as = nullptr;
	KLineSceneWidget*ptr = nullptr;
	try {
		as = (AstScene*)in[0].u.ptr;
		ptr = dynamic_cast<KLineSceneWidget*>(as->widget());
		//doc = ptr->textDocument();
	}
	catch (...) {
		//doc = nullptr;
	}

	if (!ptr)
		return -1;

	// 第二个参数
	struct astring_s*str = (struct astring_s*)in[1].u.ptr;
	QString view_name = str->value;
	// 第三个参数
	IVector*open = (IVector*)in[2].u.ptr;
	// 第四个参数
	IVector*close = (IVector*)in[3].u.ptr;
	// 第五个参数
	IVector*high = (IVector*)in[4].u.ptr;
	// 第六个参数
	IVector*low = (IVector*)in[5].u.ptr;

	KLineCanvas*canvas = ptr->canvas();

	KLineView*view = canvas->view(view_name);
	KLineBarLayer*pk = new KLineBarLayer(view);
	pk->setName("kline");
	//pk->setViewContext(view->context());
	pk->setData(KLineBarLayer::OPEN, open->data());
	pk->setData(KLineBarLayer::CLOSE, close->data());
	pk->setData(KLineBarLayer::HIGH, high->data());
	pk->setData(KLineBarLayer::LOW, low->data());
	view->setMainLayer(pk);
	canvas->recalc();
	canvas->update();

	return 0;
}

AstFunction* KLineAddBarFunction::operator()()
{
	return dynamic_cast<AstFunction*>(this);
}

QString KLineAddBarFunction::name()
{
	return ID(); //"KLineAddBar";
}
int* KLineAddBarFunction::outputTypes()
{
	return private_ptr->out_params;
}
int KLineAddBarFunction::outputCount()
{
	return private_ptr->out_count;
}
int* KLineAddBarFunction::inputTypes()
{
	return private_ptr->in_params;
}
int KLineAddBarFunction::inputCount()
{
	return private_ptr->in_count;
}
void* KLineAddBarFunction::function()
{
	return KLineAddBarFunction_FUNCTION;
}
